
sleep = (s)=>
  new Promise(
    (resolve)=>
      setTimeout(
        resolve
        s*1000
      )
  )

do =>
  i = 0
  domain = document.domain
  p = domain.split('.')
  now = new Date()
  s = now.getTime()
  now.setTime(s+999)
  v = '_' + s + '=' + s
  while i < p.length - 1 and document.cookie.indexOf(v) == -1
    domain = p.slice(-1 - ++i).join('.')
    document.cookie = v + ';expires='+ now.toUTCString() + ';domain=' + domain + ';'
  document.domain = domain
  return

cookie_rm = (cookieName)->
  domain = document.domain
  pathNodes = location.pathname.split('/').map((pathWord) ->
    '/' + pathWord
  )
  cookPaths = [ '' ].concat(pathNodes.map((pathNode) ->
    if @pathStr
      @pathStr += pathNode
    else
      @pathStr = '; path='
      return @pathStr + pathNode
    @pathStr
  ))

  (cookie_rm = (cookieName) ->
    #--- For each path, attempt to delete the cookie.
    cookPaths.forEach (pathStr) ->
      #--- To delete a cookie, set its expiration date to a past value.
      diagStr = cookieName + '=' + pathStr + '; expires=Thu, 01-Jan-1970 00:00:01 GMT;'
      document.cookie = diagStr
      document.cookie = cookieName + '=' + pathStr + '; domain=' + domain + '; expires=Thu, 01-Jan-1970 00:00:01 GMT;'
      return
    return
  ) cookieName
  return


cookie_reset = ->
  cookieList = document.cookie.split(/;\s*/)
  J = cookieList.length - 1
  while J >= 0
    cookieName = cookieList[J].replace(/\s*(\w+)=.+$/, '$1')
    cookie_rm cookieName
    --J
  return

HTTPS = "https:"

$.postJSON = (url, data, success)->
    if typeof(data) != 'string'
        data = JSON.stringify(data)
        contentType = "application/json"
    else
        contentType = "text/plain"
    $.ajax(
        url
        {
            type: 'POST'
            contentType
            data
            processData: false
            success
        }
    )

# $.get = (url)=>
#   new Promise (resolve, reject)=>
#     GM_xmlhttpRequest({
#       url
#       method: 'GET'
#       onload: (response) =>
#         resolve(response.responseText)
#     })

{pathname} = location

SEARCH = "?+"

BODY = $('body')

dump = =>
  r = []
  for i in $("div[data-poiid]")
    i = $ i
    poi = i.data('poiid') - 0
    #
    li = [
      poi
      i.find('.link.item-title')[0].href.split("://").pop()
    ]
    for css in [
      'item-title'
      'address'
      'item-eval-info span:eq(1)'
      'item-eval-info .highlight'
      'avg-price'
    ]
      li.push i.find("."+css).text()
    li[4] = ( li[4].replace('分','')*10 ) or 0
    li[5] = li[5].replace('人评论','')-0 or 0
    li[6] = li[6].replace('人均¥','')-0 or 0
    r.push li
  return r

nexted = (next, id)=>
  new Promise(
    (resolve)=>
      r = setInterval(
        =>

          if id != ($("div[data-poiid]:first").data('poiid') - 0)
            clearInterval r
            resolve()
          else
            next.click()
        1000
      )
  )

class Req
  constructor:(@base)->
  get:(url)->
    $.get(@base+url)

  postJSON:(url, data)->
    arguments[0] = @base+arguments[0]
    $.postJSON.apply @,arguments

API_URL = "//tma.xvc.com/meituan/"
API = new Req(API_URL)

进度 = (city)=>
  (1+CITY_EN.indexOf(city)) / CITY_EN.length

do =>
  begin = new Date/1000
  if location.pathname == "/error/403"
    cookie_reset()
    if history.length > 1
      history.back()
    return

  if pathname.startsWith("/s/")
    _keyword = pathname.split("/")[2]
    keyword = decodeURIComponent(_keyword)
    city = location.hostname.split(".")[0]

    next_city = =>
      if city
        pos = CITY_EN.indexOf(city) + 1
      else
        pos = 0
      if pos >= CITY_EN.length
        await API.postJSON "end/#{_keyword}"
        location.href = API_URL + _keyword + ".csv"
      else
        location.href = "//#{CITY_EN[pos]}.meituan.com/s/#{_keyword}"+SEARCH


    if location.search == SEARCH
      BODY.addClass "disable"

      runed = 进度 city
      title = Math.round(10000*runed)/100 + "% · "+document.title

      $ =>

        while 1
          document.title = title
          li = dump()
          if li.length
            await API.postJSON "city", [city, keyword].concat li

          next = $(".mt-pagination .next-btn.active")
          if next[0]
            await sleep(6)
            next.click()
            if li[0]
              await nexted(next, li[0][0])
            else
              break
          else
            break

        await API.postJSON "city/#{city}/#{_keyword}"

        next_city()


    else
      $ =>
        aCsv = $("<a class=sA>导出</a>")
        $(".header-search-block").append(aCsv)
        aCsv.click ->
          aCsv.hide()
          city = await API.get("q/"+keyword)
          next_city()


  BODY.show()



#   TestObject = AV.Object.extend('TestObject')

#   number = 2018
#   string = number + ' 流行音乐榜单'
#   date   = new Date()
#   array  = [string, number]
#   object = {
#     number: number,
#     string: string
#   }

#   pointer = AV.Object.createWithoutData('Todo', '582570f38ac247004f39c24b')

#   testObject = new TestObject()
#   testObject.set('testNumber',  number)
#   testObject.set('testString',  string)
#   testObject.set('testDate',    date)
#   testObject.set('testArray',   array)
#   testObject.set('testObject',  object)
#   testObject.set('testNull',    null)
#   testObject.set('testPointer', pointer)
#   testObject.save()
